package com.example.group.network.express_plus_app.data;


import android.app.Application;

import android.text.TextUtils;

import com.example.group.network.express_plus_app.Dao.AppDatabase;
import com.example.group.network.express_plus_app.Dao.UserDao.UserDao;
import com.example.group.network.express_plus_app.MainApplication;
import com.example.group.network.express_plus_app.data.model.LoggedInUser;

/**
 * Class that requests authentication and user information from the remote data source and
 * maintains an in-memory cache of login status and user credentials information.
 */
public class LoginRepository {

    private static volatile LoginRepository instance;

    private LoginDataSource dataSource;
    AppDatabase appDatabase;
    UserDao userDao;
    private LoggedInUser user = null;
    Application application;
    // private constructor : singleton access
    private LoginRepository(LoginDataSource dataSource,Application application) {
        this.dataSource = dataSource;
        this.application=application;
        appDatabase=AppDatabase.getsInstance(application);
        userDao=appDatabase.userDao();
    }

    public static LoginRepository getInstance(LoginDataSource dataSource,Application application) {
        if (instance == null) {
            instance = new LoginRepository(dataSource,application);
        }
        return instance;
    }

    //用户是否登录
    public boolean isLoggedIn() {
        return user != null;
    }

    public void logout() {
        user = null;
        //dataSource.logout();
        MainApplication mainApplication=MainApplication.getInstance();
        String phone = mainApplication.mInfoMap.get("phone");
        if (!TextUtils.isEmpty(phone)){
            LoggedInUser loggedInUser=new LoggedInUser(phone);
            userDao.delete(loggedInUser);
        }
        mainApplication.mInfoMap.remove("phone");
    }

    //在这个方法里将用户凭证和用户信息保存到共享参数中
    //将user信息保存到数据库
    public void setLoggedInUser(LoggedInUser user) {
        userDao.insertUser(user);
        this.user = user;
    }

    public void login(String username, String password) {
        // handle login
        dataSource.login(username, password,application);

    }
}